package com.sdtele.tta.operation;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.sdtele.tta.dac.Dac;
import com.sdtele.tta.models.JsonRequest;
import com.sdtele.tta.models.JsonResponse;
import com.sdtele.tta.models.Team;
import com.sdtele.tta.models.User;
import com.sdtele.tta.utils.TeamUtils;

/**
 * 操作类实现：GetUser(json.operation=getUser)
 * 
 * @author XCream
 */
public class OperationChgTeam extends Operation {

	@Override
	public JsonResponse handle(JsonRequest jsonRequest) {
		JsonResponse jres = new JsonResponse();
		User curUser = (User) request.getSession().getAttribute("user");

		if (curUser != null) {
			long teamId = jsonRequest.getJsonObject().get("teamId").getAsLong();
			Team team = Dac.getInstance().getTeam(teamId);
			String teamName = jsonRequest.getJsonObject().get("teamName").getAsString();
			Long upTeamId = jsonRequest.getJsonObject().get("upTeamId").getAsLong();
			JsonElement cityName = jsonRequest.getJsonObject().get("cityName");
			JsonElement cityid = jsonRequest.getJsonObject().get("cityId");			
			team.setTeamName(teamName);
			team.setUpTeamId(upTeamId);
			if (cityName!=null && !(cityName.getAsString().isEmpty())) {
				team.setCityName(cityName.getAsString());
			}
			if (cityid!=null && !(cityid.getAsString().isEmpty())) {
				int cityId=Integer.parseInt(cityid.getAsString());
				team.setCityID(cityId);
			}				
			if (curUser.getIsManager() == 1) {
				Set<Long> teamIdSet = new HashSet<Long>();
				teamIdSet.add(curUser.getTeamId());
				TeamUtils.teamAuthority(curUser.getTeamId(), teamIdSet);				
				if (!(teamIdSet.contains(upTeamId))) {
					if(curUser.getTeamId()==teamId) {
						if(upTeamId!=Dac.getInstance().getTeam(curUser.getTeamId()).getUpTeamId()) {
							jres.setStatus(1);
							jres.setMessage("权限不够修改该组织");
						}else {
							if (Dac.getInstance().chgTeam(team)) {
								jres.setStatus(0);
								jres.setMessage("修改组织成功");
								jres.setEntity(team);
							} else {
								jres.setStatus(1);
								jres.setMessage("未知错误，修改组织失败");
							}
						}
					}else {
						jres.setStatus(1);
						jres.setMessage("权限不够修改该组织");
					}					
				} else {
					if (Dac.getInstance().chgTeam(team)) {
						jres.setStatus(0);
						jres.setMessage("修改组织成功");
						jres.setEntity(team);
					} else {
						jres.setStatus(1);
						jres.setMessage("未知错误，修改组织失败");
					}
				}
			} else {
				jres.setStatus(1);
				jres.setMessage("用户不是管理员，不能修改组织机构");
			}
		} else {
			jres.setStatus(1);
			jres.setMessage("用户未登录");
		}

		return jres;
	}

}
